package com.nineclock.attendance.job;

import com.nineclock.attendance.mapper.AttendGroupMapper;
import com.nineclock.attendance.pojo.AttendGroup;
import com.nineclock.attendance.service.AttendPunchService;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SendAttendMailTask {

    @Autowired
    private AttendGroupMapper attendGroupMapper;

    @Autowired
    private AttendPunchService attendPunchService;

    @Autowired
    private SysUserFeign sysUserFeign;

    /**
     * 统计所有统计企业本月考勤数据
     *
     * @throws MessagingException
     */
    @XxlJob("countAttendanceAndSendMail")
    public void countAttendanceAndSendMail() throws MessagingException, IOException {

        //1. 获取所有的企业ID集合
        List<Long> companyIds = this.queryCompanyIds();

        for (Long companyId : companyIds) {
            //2. 遍历企业,根据打卡情况 构造Excel文件 ---> 统计每个的企业的本月考勤情况 ;
            String excelFile = attendPunchService.generateExcelReportByCompanyId(companyId);

            //3. 获取每一个企业主管理员邮箱
            //调用Feign接口 查询企业管理员的信息
            SysCompanyUserDTO userDTO = sysUserFeign.queryAdminByCompanyId(companyId).getData();

            //4. 调用JavaMail发送邮件
            this.sendMail(userDTO, excelFile);
        }
    }

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    //发送附件邮件给企业的主管理员
    private void sendMail(SysCompanyUserDTO userDTO, String excelFile) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

        messageHelper.setFrom(from);
        //messageHelper.setTo(userDTO.getEmail());
        messageHelper.setTo("510320359@163.com");
        messageHelper.setSubject("考勤数据报表");
        messageHelper.setText("您好, 本月考勤数据报表已经生成, 请查收附件, 谢谢");

        messageHelper.addAttachment("本月考勤数据.xls", new File(excelFile));

        javaMailSender.send(mimeMessage);

    }

    //获取所有的配置类考勤组的 企业ID集合
    private List<Long> queryCompanyIds() {

        List<AttendGroup> attendGroups = attendGroupMapper.selectList(null);
        List<Long> ids = attendGroups.stream().map(attendGroup -> {
            return attendGroup.getCompanyId();
        }).collect(Collectors.toList());
        return ids;
    }
}